<template>
  <div class="item-manage">
    <div class="header">
      <h2>奖品管理</h2>
      <button class="add-btn" @click="showAddDialog = true">添加奖品</button>
    </div>

    <table>
      <thead>
        <tr>
          <th>奖品ID</th>
          <th>奖品名称</th>
          <th>所需积分</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in itemList" :key="item.ItemId">
          <td>{{ item.ItemId }}</td>
          <td>{{ item.ItemName }}</td>
          <td>{{ item.ItemScore }}</td>
          <td>
            <button class="edit-btn" @click="handleEdit(item)">编辑</button>
            <button class="delete-btn" @click="handleDelete(item.ItemId)">
              删除
            </button>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- 添加/编辑奖品对话框 -->
    <div v-if="showAddDialog || showEditDialog" class="dialog-overlay">
      <div class="dialog">
        <h3>{{ showEditDialog ? "编辑奖品" : "添加奖品" }}</h3>
        <form @submit.prevent="handleSubmit">
          <div class="form-item">
            <label>奖品名称：</label>
            <input v-model="itemForm.ItemName" required />
          </div>
          <div class="form-item">
            <label>所需积分：</label>
            <input v-model="itemForm.ItemScore" type="number" required />
          </div>
          <div v-if="imagePreview" class="image-preview">
            <img :src="imagePreview" alt="图片预览" />
          </div>
          <div class="dialog-actions">
            <button type="submit">确定</button>
            <button type="button" @click="closeDialog">取消</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 图片预览对话框 -->
    <div
      v-if="showImagePreview"
      class="preview-overlay"
      @click="showImagePreview = false"
    >
      <div class="preview-content" @click.stop>
        <img :src="previewImageUrl" alt="预览图片" class="preview-image" />
        <div class="preview-close" @click.stop="showImagePreview = false">
          ×
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from "vue";
import {
  getItemList,
  addItem,
  updateItem,
  deleteItem,
  getItemPhotoUrl,
} from "@/api/item";

interface Item {
  ItemId: number;
  ItemName: string;
  ItemPhoto: string | null;
  ItemScore: number;
}

const itemList = ref<Item[]>([]);
const showAddDialog = ref(false);
const showEditDialog = ref(false);
const imagePreview = ref("");
const itemForm = ref({
  ItemId: "",
  ItemName: "",
  ItemScore: "",
  ItemPhoto: null as File | null,
});

// 添加预览相关的响应式变量
const showImagePreview = ref(false);
const previewImageUrl = ref("");

// 获取图片URL并转换为显示URL
const getPhotoUrl = async (itemId: string): Promise<string> => {
  try {
    console.log("开始获取图片URL, itemId:", itemId);
    const res = await getItemPhotoUrl(itemId);
    console.log("getItemPhotoUrl返回数据:", res);
    if (res.code === "200" && res.data && res.data.length > 0) {
      const fullUrl = res.data[0];
      console.log("获取到的URL:", fullUrl);
      // 从URL中提取出年月日/文件名部分
      const parts = fullUrl.split("5000/");
      if (parts.length === 2) {
        const pathPart = parts[1]; // 例如：2025030427/food.jpg
        console.log("提取出的路径部分:", pathPart);
        // 构造使用showphoto的URL
        const showPhotoUrl = `http://8.140.225.174:5000/showphoto/${pathPart}`;
        console.log("构造的showphoto URL:", showPhotoUrl);
        return showPhotoUrl;
      }
    }
    console.log("未能获取到有效的图片URL");
    return "";
  } catch (error) {
    console.error("获取图片URL错误:", error);
    return "";
  }
};

// 获取奖品列表
const fetchItemList = async () => {
  try {
    // 添加小延时确保后端数据更新
    await new Promise((resolve) => setTimeout(resolve, 100));
    const res = await getItemList();
    if (res.code === 200) {
      itemList.value = res.data;
      // 获取每个奖品的图片URL
      for (const item of itemList.value) {
        if (item.ItemPhoto) {
          item.ItemPhoto = await getPhotoUrl(String(item.ItemId));
        }
      }
    } else {
      throw new Error(res.message || "获取列表失败");
    }
  } catch (error: any) {
    console.error("获取列表错误:", error);
    alert(error.message);
  }
};

// 处理文件选择
const handleFileChange = (e: Event) => {
  const target = e.target as HTMLInputElement;
  if (target.files && target.files[0]) {
    const file = target.files[0];
    itemForm.value.ItemPhoto = file;
    // 创建预览URL
    imagePreview.value = URL.createObjectURL(file);
  }
};

// 编辑奖品
const handleEdit = (item: Item) => {
  itemForm.value = {
    ItemId: String(item.ItemId),
    ItemName: item.ItemName,
    ItemScore: String(item.ItemScore),
    ItemPhoto: null,
  };
  // 如果有原图片，显示原图片
  imagePreview.value = item.ItemPhoto || "";
  showEditDialog.value = true;
};

// 删除奖品
const handleDelete = async (itemId: number) => {
  if (!confirm("确定要删除该奖品吗？")) return;
  try {
    const res = await deleteItem(String(itemId));
    if (res.code === 200) {
      // 删除成功后重新获取列表
      await fetchItemList();
      alert("删除成功");
    } else {
      throw new Error(res.message || "删除失败");
    }
  } catch (error: any) {
    console.error("删除错误:", error);
    alert(error.message);
    // 发生错误时也重新获取列表
    await fetchItemList();
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    const formData = new FormData();
    formData.append("ItemName", itemForm.value.ItemName);
    formData.append("ItemScore", itemForm.value.ItemScore);

    if (showEditDialog.value) {
      // 编辑模式：只添加ItemId，不处理图片
      formData.append("ItemId", itemForm.value.ItemId);
    } else {
      // 新增模式：处理图片
      if (itemForm.value.ItemPhoto instanceof File) {
        formData.append("ItemPhoto", itemForm.value.ItemPhoto);
      }
    }

    // 打印FormData的内容
    console.log(showEditDialog.value ? "编辑" : "新增", "奖品，传递的数据:");
    formData.forEach((value, key) => {
      if (value instanceof File) {
        console.log(
          key + ":",
          "文件名:",
          value.name,
          "大小:",
          value.size,
          "bytes"
        );
      } else {
        console.log(key + ":", value);
      }
    });

    const res = await (showEditDialog.value
      ? updateItem(formData)
      : addItem(formData));

    if (res.code === 200) {
      closeDialog();
      await fetchItemList();
      alert(showEditDialog.value ? "编辑成功" : "添加成功");
    } else {
      throw new Error(
        res.message || (showEditDialog.value ? "编辑失败" : "添加失败")
      );
    }
  } catch (error: any) {
    console.error("提交错误:", error);
    alert(error.message);
  }
};

// 关闭对话框
const closeDialog = () => {
  showAddDialog.value = false;
  showEditDialog.value = false;
  itemForm.value = {
    ItemId: "",
    ItemName: "",
    ItemScore: "",
    ItemPhoto: null,
  };
  imagePreview.value = "";
};

// 添加图片预览处理函数
const handlePreviewImage = (url: string) => {
  previewImageUrl.value = url;
  showImagePreview.value = true;
};

onMounted(() => {
  fetchItemList();
});
</script>

<style scoped>
.item-manage {
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 10px;
}

.add-btn {
  background-color: #409eff;
  color: white;
  border: none;
  padding: 8px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: opacity 0.2s;
}

.add-btn:hover {
  opacity: 0.9;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
}

th,
td {
  padding: 15px 20px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

th {
  background-color: #f5f7fa;
  font-weight: 500;
  color: #606266;
  font-size: 14px;
}

td {
  font-size: 14px;
  color: #606266;
}

.item-photo {
  max-width: 100px;
  max-height: 60px;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.2s;
  object-fit: cover;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.item-photo:hover {
  transform: scale(1.05);
}

.edit-btn,
.delete-btn {
  padding: 6px 12px;
  margin-right: 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  transition: opacity 0.2s;
}

.edit-btn:hover,
.delete-btn:hover {
  opacity: 0.9;
}

.edit-btn {
  background-color: #409eff;
  color: white;
}

.delete-btn {
  background-color: #f56c6c;
  color: white;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog {
  background: white;
  padding: 25px;
  border-radius: 8px;
  width: 400px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.dialog h3 {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 18px;
}

.form-item {
  margin-bottom: 20px;
}

.form-item label {
  display: block;
  margin-bottom: 8px;
  color: #606266;
  font-size: 14px;
}

.form-item input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
  transition: border-color 0.2s;
}

.form-item input:focus {
  outline: none;
  border-color: #409eff;
}

.dialog-actions {
  margin-top: 25px;
  text-align: right;
}

.dialog-actions button {
  padding: 8px 20px;
  margin-left: 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: opacity 0.2s;
}

.dialog-actions button[type="submit"] {
  background-color: #409eff;
  color: white;
}

.dialog-actions button[type="button"] {
  background-color: #909399;
  color: white;
}

.dialog-actions button:hover {
  opacity: 0.9;
}

.image-preview {
  margin-top: 10px;
  text-align: center;
}

.image-preview img {
  max-width: 200px;
  max-height: 120px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 添加预览相关样式 */
.preview-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
}

.preview-content {
  position: relative;
  max-width: 90vw;
  max-height: 90vh;
}

.preview-image {
  max-width: 100%;
  max-height: 90vh;
  object-fit: contain;
}

.preview-close {
  position: absolute;
  top: -40px;
  right: -40px;
  width: 40px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  color: white;
  font-size: 30px;
  cursor: pointer;
}
</style>
